package cn.edu.hqu.cst.chapter0204.web;

import cn.edu.hqu.cst.chapter0204.domain.Ingredient;
import cn.edu.hqu.cst.chapter0204.domain.Ingredient.Type;
import cn.edu.hqu.cst.chapter0204.domain.Taco;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/design")
@SessionAttributes("design")
public class DesignTacoController {
    private static final Logger log = (Logger) LoggerFactory.getLogger(DesignTacoController.class);

    public DesignTacoController() {
    }

    @ModelAttribute
    public void addIngredientsToModel(Model model) {
        List<Ingredient> ingredients = Arrays.asList(new Ingredient("NUM1", "生活中的统计学", Type.CLASS1), new Ingredient("NUM2", "境外游学法律护佑（混合式学习）", Type.CLASS1), new Ingredient("NUM3", "“一带一路”战略与全球法治", Type.CLASS2), new Ingredient("NUM4", "中国公务员制度实务", Type.CLASS2), new Ingredient("NUM5", "中国古代科技成就与启示", Type.CLASS3), new Ingredient("NUM6", "环境保护与可持续发展（混合式学习）", Type.CLASS3), new Ingredient("NUM7", "古代中国人的日常生活与文化习俗", Type.CLASS4), new Ingredient("NUM8", "奥林匹克运动文化", Type.CLASS4), new Ingredient("NUM9", "西方音乐剧鉴赏（全英文）", Type.CLASS5), new Ingredient("NUM0", "中西方舞蹈的欣赏与审美比较", Type.CLASS5));
        Type[] types = Type.values();
        Type[] var7 = types;
        int var6 = types.length;

        for (int var5 = 0; var5 < var6; ++var5) {
            Type type = var7[var5];
            model.addAttribute(type.toString().toLowerCase(), this.filterByType(ingredients, type));
        }

    }

    @GetMapping
    public String showDesignForm(Model model) {
        model.addAttribute("design", new Taco());
        return "design";

    }

    @PostMapping//处理POST动作,@ModelAttribute注解自动将model中的数据注入到修饰的参数
    public String processDesing(@Valid @ModelAttribute("design") Taco design, Errors errors, Model model) {
        if (errors.hasErrors()) {
            return "design";
        }
        log.info("Processing design:" + design);
        return "redirect:/orders/current";


    }

    private List<Ingredient> filterByType(
            List<Ingredient> ingredients, Type type) {
        return ingredients
                .stream()
                .filter(x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }

}
